//
//  QSClearCacheTool.swift
//  TestSwift
//
//  Created by Song on 2018/12/13.
//  Copyright © 2019 Song. All rights reserved.
//

import UIKit

class QSClearCacheTool {
    /// 计算缓存大小（M）
    class func qs_caculateCache() -> String {
        let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let path = paths.first
        let fileManger = FileManager.default
        
        var total: CGFloat = 0.0
        if fileManger.fileExists(atPath: path!) {
            let childrenPath = fileManger.subpaths(atPath: path!)
            if childrenPath != nil {
                for p in childrenPath! {
                    let childPath = path! + "/" + p
                    
                    let attr: Dictionary? = try? fileManger.attributesOfItem(atPath: childPath)
                    if let att = attr {
                        let fileSize = att[.size] as! CGFloat
                        total += fileSize
                    }
                }
            }
        }
        
        let cacheSize = String.init(format: "%.1f", total / 1024.0 / 1024.0)
        return cacheSize
    }
    
    /// 清除缓存
    class func qs_clearCache() {
        let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let path = paths.first
        let fileManger = FileManager.default
        
        if fileManger.fileExists(atPath: path!) {
            let childrenPath = fileManger.subpaths(atPath: path!)
            if childrenPath != nil {
                for p in childrenPath! {
                    let childPath = path! + "/" + p
                    try? fileManger.removeItem(atPath: childPath)
                }
            }
        }
    }
}
